package com.metaera.app.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.material.animation.ArgbEvaluatorCompat;
import com.google.android.material.appbar.AppBarLayout;
import com.jaeger.library.StatusBarUtil;
import com.lxj.xpopup.XPopup;
import com.metaera.app.LocalConfigStore;
import com.metaera.app.R;
import com.metaera.app.controller.presenter.FollowAuthorPresenter;
import com.metaera.app.controller.presenter.ProfilePresenter;
import com.metaera.app.controller.view.BasicNetworkRequestView;
import com.metaera.app.controller.view.FollowAuthorView;
import com.metaera.app.data.model.UserDetailsResponse;
import com.metaera.app.data.network.ApiParam;
import com.metaera.app.ui.adapters.SimpleFragmentStatePagerAdapter;
import com.metaera.app.ui.adapters.navigator.FlashNewsNavigatorAdapter;
import com.metaera.app.ui.core.BaseActivity;
import com.metaera.app.ui.fragments.UserInformationListFragment;
import com.metaera.app.ui.popup.ShareUserPopup;
import com.metaera.app.ui.popup.ShareUserProfilePopup;
import com.metaera.app.ui.popup.UserPlatformPopup;
import com.metaera.app.utils.LoginClickListener;
import com.metaera.app.utils.ViewUtils;
import com.metaera.app.utils.image.GlideApp;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;

import java.util.ArrayList;
import java.util.Collections;

import androidx.viewpager.widget.ViewPager;

/**
 * 用户主页
 */
public class UserProfileActivity extends BaseActivity {

    public static Intent newIntent(Context context, int uid) {
        return new Intent(context, UserProfileActivity.class).putExtra("EXTRA_UID", uid);
    }

    @Override
    protected void initStatusBar() {
        StatusBarUtil.setTranslucentForImageViewInFragment(this, 0, null);
        StatusBarUtil.setDarkMode(this);
    }

    @Override
    protected int getContentLayoutId() {

        return R.layout.activity_user_profile;
    }

    @Override
    protected void initialize(Bundle savedInstanceState) {
        View layoutTitleContainer = findViewById(R.id.layout_title_container);
        ViewUtils.addStatusBarHeightPadding(layoutTitleContainer);

        // find
        ImageView ivAvatar = findViewById(R.id.iv_avatar);
        TextView tvNickname = findViewById(R.id.tv_nickname);
        TextView tvTitleNickname = findViewById(R.id.tv_title_nickname);
        TextView tvSignature = findViewById(R.id.tv_signature);
        TextView tvFollowNumber = findViewById(R.id.tv_follow_number);
        TextView buttonFollow = findViewById(R.id.button_follow);
        TextView buttonTitleFollow = findViewById(R.id.button_title_follow);
        ImageView ivSettings = findViewById(R.id.iv_settings);
        ImageView ivReport = findViewById(R.id.iv_report);
        ImageView ivShare = findViewById(R.id.iv_share);
        TextView tvFansNumber = findViewById(R.id.tv_fans_number);
        TextView tvViewsNumber = findViewById(R.id.tv_views_number);
        AppBarLayout appBarLayout = findViewById(R.id.app_bar_layout);
        MagicIndicator magicIndicator = findViewById(R.id.magic_indicator);
        ViewPager viewPager = findViewById(R.id.view_pager);

        findViewById(R.id.iv_arrow_back).setOnClickListener(v->finish());

        // init
        int uid = getIntent().getIntExtra("EXTRA_UID", 0);
        if (LocalConfigStore.getInstance().isLogin()) { // 已登录
            UserDetailsResponse user = LocalConfigStore.getInstance().getUser();
            if (user.getId() == uid) { // 自己的页面
                ivSettings.setVisibility(View.VISIBLE);
                ViewUtils.setVisibility(View.GONE, buttonFollow, ivReport, buttonTitleFollow);

                ivSettings.setOnClickListener(new LoginClickListener(v -> startActivity(UserEditCenterActivity.class)));

            } else {
                ivSettings.setVisibility(View.GONE);
            }

        } else {

            ivSettings.setOnClickListener(v -> startActivity(LoginActivity.class));
            // buttonFollow.setOnClickListener(v -> startActivity(LoginActivity.class));
        }

        CommonNavigator commonNavigator = new CommonNavigator(viewPager.getContext());
        commonNavigator.setAdapter(new FlashNewsNavigatorAdapter(
                viewPager,
                new ArrayList<>(Collections.singletonList(getString(R.string.article_number_placeholder)))
        ));

        // 导航器设置适配器
        magicIndicator.setNavigator(commonNavigator);
        viewPager.setAdapter(new SimpleFragmentStatePagerAdapter(
                getSupportFragmentManager(),
                new ArrayList<>(Collections.singletonList(UserInformationListFragment.newInstance(uid))))
        );

        // network
        ProfilePresenter presenter = new ProfilePresenter();
        presenter.setModelAndView(new BasicNetworkRequestView<>(data -> {
            tvNickname.setText(data.getNickname());

            if (!TextUtils.isEmpty(data.getDesc())) {
                tvSignature.setText(data.getDesc());
            }

            tvFollowNumber.setText(String.valueOf(data.getFollow_num()));
            tvFansNumber.setText(String.valueOf(data.getFans_num()));
            tvViewsNumber.setText(String.valueOf(data.getVisits_num()));
            tvTitleNickname.setText(data.getNickname());

            buttonFollow.setSelected(data.getIs_follow() == ApiParam.FOLLOW_AUTHOR);
            buttonFollow.setText(buttonFollow.isSelected() ? R.string.followed : R.string.follow);

            GlideApp.with(this).load(data.getAvatar_img()).avatar().into(ivAvatar);

            //if (buttonFollow.getVisibility() != View.GONE) {
                ivShare.setOnClickListener(
                        v -> new XPopup.Builder(v.getContext())
                                .asCustom(new ShareUserProfilePopup(v.getContext(), data))
                                .show())
                ;
            //}

            tvSignature.setOnClickListener(
                    v -> new XPopup.Builder(v.getContext())
                    .asCustom(new UserPlatformPopup(v.getContext(), data))
                    .show());

            findViewById(R.id.image).setOnClickListener(
                    v-> new XPopup.Builder(v.getContext())
                            .asCustom(new ShareUserPopup(v.getContext(), data))
                            .show()
            );

            FollowAuthorPresenter followAuthorPresenter = new FollowAuthorPresenter();
            followAuthorPresenter.setModelAndView(new FollowAuthorView(buttonFollow));
            buttonFollow.setOnClickListener(new LoginClickListener(v -> followAuthorPresenter.follow(data.getId(), !v.isSelected())));
        }));

        presenter.execute(uid);

        // listener


        appBarLayout.addOnOffsetChangedListener((appBarLayout1, verticalOffset) -> {

            int totalScrollRange = appBarLayout1.getTotalScrollRange();
            float ratio = Math.abs((float) verticalOffset / totalScrollRange);
            layoutTitleContainer.setBackgroundColor(ArgbEvaluatorCompat.getInstance()
                    .evaluate(ratio, Color.TRANSPARENT, Color.WHITE));

            if (ratio < 0.95 && tvTitleNickname.getVisibility() != View.INVISIBLE) {
                StatusBarUtil.setDarkMode(this);
                tvTitleNickname.setVisibility(View.INVISIBLE);

            } else if (ratio > 0.95 && tvTitleNickname.getVisibility() != View.VISIBLE) {
                StatusBarUtil.setLightMode(this);
                tvTitleNickname.setVisibility(View.VISIBLE);
            }

        });
    }

}
